<script setup lang="ts">
import { ref, useTemplateRef, onActivated, onDeactivated } from 'vue'
import { useScrollGroup } from '@/hooks/reno14-pro.ts'
import { useGsapContext } from '@/hooks'
import { ScrollTrigger } from 'gsap/ScrollTrigger'

defineProps<{
  type: 'img' | 'video'
  src: string
}>()

const { scrollGroup } = useScrollGroup()

useGsapContext(() => {
  if (!videoRef.value) {
    return
  }

  ScrollTrigger.create({
    trigger: videoRef.value,
    start: 'top bottom',
    end: 'bottom top',
    onToggle: async (self) => {
      if (self.isActive) {
        await videoPlay()
      } else {
        videoStop()
      }
    },
    invalidateOnRefresh: true,
    ...scrollGroup,
  })
})

const videoRef = useTemplateRef<HTMLVideoElement | null>('videoRef')
const videoPlay = async () => {
  if (!videoRef.value) {
    return
  }

  await videoRef.value.play().catch()
}
const videoStop = () => {
  if (!videoRef.value) {
    return
  }

  videoRef.value.pause()
  videoRef.value.currentTime = 0
}

const showReply = ref(false)

onActivated(async () => {
  await videoPlay()
})
onDeactivated(videoStop)
</script>

<template>
  <div class="">
    <div v-if="type === 'video'" class="relative">
      <video
        ref="videoRef"
        class="absolute w-[40%] aspect-[200/422] inset-0 m-auto rounded-2xl object-fill sm:w-[37%] lg:w-[59.5%]"
        muted
        autoplay
        :src
        @play="showReply = false"
        @ended="showReply = true"
      ></video>
      <img
        class="w-[41%] aspect-[200/422] relative z-1 mx-auto sm:w-[38%] lg:w-[61%]"
        src="@/views/product/reno14-pro/image/6/images-coloros-frame-pc-1.png.webp"
        alt=""
        loading="lazy"
      />

      <img
        v-show="showReply"
        class="w-[2.25rem] aspect-square absolute bottom-0 right-[10%] z-1 lg:right-0"
        src="@/views/product/reno14-pro/image/6/images-coloros-replay-1.svg"
        alt=""
        loading="lazy"
        @click="videoPlay"
      />
    </div>

    <img
      v-else
      class="w-[41%] mx-auto object-contain aspect-[200/422] sm:w-[38%] lg:w-[61%]"
      :src
      alt=""
      loading="lazy"
    />
  </div>
</template>
